package org.geekbang.time.mathbasicthought.lesson3_iteration;

public class SquareRoot {

    public static void main(String[] args) {
        double squareRoot = getSquareRoot(10, 0.000001, 10000);
        if (squareRoot == -1.0)
            System.out.println("请输入正整数");
        else if (squareRoot == -2.0)
            System.out.println("无法计算");
        else
            System.out.println(String.format("%d的平方根是%f", 10, squareRoot));
    }

    /**
     * @param targetNumber   要求解的值
     * @param deltaThreshold 误差阈值
     * @param maxTry         最大迭代次数，防止死循环
     * @return 平方根的近似值
     */
    public static double getSquareRoot(int targetNumber, double deltaThreshold, int maxTry) {
        if (targetNumber < 1) {
            return -1.0;
        }

        double min = 1.0, max = targetNumber;
        for (int i = 0; i < maxTry; i++) {
            // 防止溢出
            double mid = min + (max - min) / 2;
            double square = mid * mid;
            // 近似值
            double delta = Math.abs(square / targetNumber - 1);
            if (delta <= deltaThreshold) {
                return mid;
            }

            if (square > targetNumber) {
                max = mid;
            } else {
                min = mid;
            }
        }

        return -2.0;
    }

}
